package com.example.villagemanager.ui.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.villagemanager.manager.DialogManager;
import com.example.villagemanager.model.event.Event;
import com.noober.background.BackgroundLibrary;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.yinglan.keyboard.HideUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity extends RxAppCompatActivity implements EasyPermissions.PermissionCallbacks {
    protected static final String TAG = "BaseActivity";
    public static final String SHAREDATA="SHAREDATA";
    private Context mContext;
    public Bundle mBundle;
    private ProgressDialog loadingDialog;
    public Uri photoUri;
    public Intent mIntent;
    public boolean isBind = false;
    boolean isPermissionGrant;// 程序是否被允许持有写入权限

    public  BluetoothAdapter btAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //BackgroundLibrary
        BackgroundLibrary.inject(this);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        mContext=this;
        mIntent=getIntent();
        //初始化布局
        setContentView(getContentView());
        //控件绑定
        ButterKnife.bind(this);

        //事件总线
        EventBus.getDefault().register(this);
        //软键盘
        HideUtil.init(this);
        requestStoragePermission();
        requestBlueToothPermission();
        initContentView();
        initActivityData();
    }

    @SuppressLint("AutoDispose")
    private void requestBlueToothPermission() {

    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }
    protected abstract void initActivityData();

    protected abstract void initContentView();

    protected abstract int getContentView();

    /**
     * 获取event
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThreadEvent(Event event) {
        if (null != event) {
            //处理事件...
            onEventProcess(event);
        }
    }
    @SuppressLint("AutoDispose")
    private void requestStoragePermission() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_SCAN,
                        Manifest.permission.BLUETOOTH_CONNECT,
                        Manifest.permission.BLUETOOTH_ADVERTISE,
                        Manifest.permission.BLUETOOTH_PRIVILEGED)
                .subscribe((Consumer<? super Boolean>) aBoolean -> isPermissionGrant = aBoolean);
    }
    /**
     * 处理event事件
     *
     * @param event
     */
    protected abstract void onEventProcess(Event event);

    /**
     * 跳转activity
     *
     * @param clazz
     */
    protected void sendIntent(Class<?> clazz) {
        sendIntent(clazz, null);
    }

    protected void sendIntent(String appPath) {
        Intent it = new Intent();
        it.setAction(appPath);
        startActivity(it);
    }
    protected void sendIntent(String appPath, Bundle bundle) {
        Intent it = new Intent();
        it.setAction(appPath);
        if (null != bundle) {
            it.putExtras(bundle);
        }
        startActivity(it);
    }
    /**
     * 跳转activity并传值
     *
     * @param clazz
     * @param bundle
     */
    protected void sendIntent(Class<?> clazz, Bundle bundle) {
        if (mIntent==null){
            mIntent=new Intent();
        }
        mIntent.setClass(this, clazz);
        if (null != bundle) {
            mIntent.putExtras(bundle);
        }
        startActivity(mIntent);
    }

    /**
     * 跳转activity获取返回
     *
     * @param clazz
     * @param requestCode
     */
    protected void sendIntentForResult(Class<?> clazz, int requestCode) {
        sendIntentForResult(clazz, requestCode, null);
    }

    /**
     * 跳转activity获取返回并传值
     *
     * @param clazz
     * @param requestCode
     * @param bundle
     */
    protected void sendIntentForResult(Class<?> clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 获取上下文对象
     * @return
     */
    public Context getContext(){
        if(mContext == null){
            mContext = this;
        }
        return mContext;
    }

    /**
     * 获取传值
     * @return
     */
    protected Bundle getBundle(){
        if (mBundle == null && getIntent() != null) {
            mBundle = getIntent().getExtras();
        }
        return mBundle;
    }

    /**
     * 加载对话框
     * @return
     */
    protected ProgressDialog getLoadingDialog(){
        if(loadingDialog == null){
            loadingDialog = DialogManager.getLoadingDialog(this);
        }
        return loadingDialog;
    }

    /**
     * 加载对话框
     * @param message
     * @return
     */
    protected ProgressDialog getLoadingDialog(String message){
        if(loadingDialog == null){
            loadingDialog = DialogManager.getLoadingDialog(this);
        }
        loadingDialog.setMessage(message);
        return loadingDialog;
    }
    /**
     * 权限申请回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions获取回调
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限授予回调
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());

    }

    /**
     * 权限禁止回调
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("权限申请").setRationale("APP可能没有获取到相关权限，是否打开设置修改权限？").build().show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK) {

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    protected void hideSystemBar(){
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions =
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }




}
